﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Data.OleDb;
using System.Runtime.InteropServices;
using System.Globalization;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Taxonomy;

namespace OrgStructure
{
    [Guid("C55D2D97-BDAF-4530-9B6C-CEAFBC0D63D6")]
    public class JobOrgStructure : SPJobDefinition
    {

        #region Members

        public override string DisplayName
        {
            get
            {
                return "(Ko) Обновление Структуры организации ; v. 1.0.0.5";
            }
        }

        public override string Description
        {
            get
            {
                return "(Ko) Обновление Структуры организации по 1С";
            }
        }

        #endregion

        #region Constructors

        public JobOrgStructure()
            : base()
        {
            this.Title = DisplayName;
        }

        public JobOrgStructure(string jobName, SPService service, SPServer server, SPJobLockType targetType)
            : base(jobName, service, server, targetType)
        {
            this.Title = DisplayName;
        }

        public JobOrgStructure(string jobName, SPWebApplication webApplication)
            : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
        {
            this.Title = DisplayName;
        }

        #endregion

        #region Common

        static public string GetAppSetting(String mName)
        {
            String vStr = null;
            SPWebService mSer = SPWebService.ContentService;
            #region Ver 1
            if (mSer != null)
            {
                foreach (SPWebConfigModification mMod in mSer.WebConfigModifications)
                {
                    if (mMod.Owner == mName)
                        vStr = mMod.Value;
                }
            }
            if (vStr != null)
            {
                vStr =
                    vStr.Substring(
                        vStr.IndexOf("value=") + 7
                        , vStr.Length - 7 - vStr.IndexOf("value=") - 4);
            }
            #endregion Ver 1
            else
            #region Ver 2
            {
                string strPath =
    @"C:\inetpub\wwwroot\wss\VirtualDirectories\80\web.config";
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(strPath);
                XmlNode node = xmlDoc.SelectSingleNode(@"/configuration/appSettings");
                foreach (XmlNode keynode in node.ChildNodes)
                {
                    string keyStr = keynode.Attributes["key"].Value;
                    if (keyStr == mName)
                    {
                        vStr = keynode.Attributes["value"].Value;
                        break;
                    }
                }
            }
            #endregion Ver 2
            if (String.IsNullOrEmpty(vStr))
                vStr = "";
            return vStr;
        }

        #endregion

        public override void Execute(Guid contentDbId)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                InvalidateStructure();
            });
        }

        public static void InvalidateStructure()
        {

            Exception err = null;

            // Invalidate
            err = OrgStructure_DLL.OrgStructure.InvalidateStructure(@"http://localhost/");

            if (err != null)
            {
                throw new Exception(err.Message, err);
            }

            /*
            DeleteOrgStructure();

            //--
            Group yGroup = null;
            TermStore yStore = null;
            SPSite site = new SPSite("http://localhost/");
            TaxonomySession mSess = new TaxonomySession(site);
            foreach (TermStore mStore in mSess.TermStores)
            {
                foreach (Group mGroup in mStore.Groups)
                    if (mGroup.Name == "Структура Организации")
                    {
                        yStore = mStore;
                        yGroup = mGroup;
                    }
            }

            //--
            using (OleDbConnection conn = new OleDbConnection(GetAppSetting(@"1CConnect")))
            {
                conn.Open();
                if (yGroup != null)
                {
                    using (OleDbCommand cmd = new OleDbCommand())
                    {
                        cmd.CommandText =
@"SELECT sp._Description as Name,sp._Code as ID,sp1._Code as ParentID 
FROM _Reference67 as sp 
LEFT JOIN _Reference67 as sp1 ON sp1._IDRRef=sp._ParentIDRRef 
WHERE sp._Code<>'09' AND sp1._Code Is Null";
                        cmd.CommandType = CommandType.Text;
                        cmd.Connection = conn;
                        using (OleDbDataReader reader = cmd.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                TermSet mSet = yGroup.CreateTermSet(reader["Name"].ToString());
                                mSet.Description = reader["ID"].ToString();
                                //--
                                CreateTreeOrg(mSet, reader["ID"].ToString());
                                //--
                                //CreateLineLog(reader["Name"].ToString());
                            }
                            reader.Close();
                        }
                        //--
                        yStore.CommitAll();
                        //--
                        conn.Close();
                    }
                }
                site.Dispose();
            }
            */
        } // InvalidateStructure()

        //public static void DeleteOrgStructure()
        //{
        //    SPSite site = new SPSite("http://localhost/");
        //    TaxonomySession mSess = new TaxonomySession(site);
        //    foreach (TermStore mStore in mSess.TermStores)
        //    {
        //        foreach (Group mGroup in mStore.Groups)
        //        {
        //            if (mGroup.Name == "Структура Организации")
        //            {
        //                foreach (TermSet mSet in mGroup.TermSets)
        //                {
        //                    mSet.Delete();
        //                }
        //            }
        //        }
        //        mStore.CommitAll();
        //    }
        //    site.Dispose();
        //}

        //public static OleDbConnection CreateSQLConnect()
        //{
        //    OleDbConnection sqlConnection1 = new OleDbConnection(); // SqlDbConnection
        //    sqlConnection1.ConnectionString = GetAppSetting(@"1CConnect");
        //    sqlConnection1.Open();
        //    return sqlConnection1;
        //}

        public void CreateLineLog(String mStr)
        {
            /*
            SPSite site = new SPSite("http://localhost");
            SPWeb mWeb = site.OpenWeb("/");
            try
            {
                SPList list = mWeb.Lists["log"];
                mWeb.AllowUnsafeUpdates = true;
                SPListItem item = list.Items.Add();
                item["Title"] = "(" + DateTime.Now.ToString() + ") " + mStr;
                item.Update();
            }
            catch
            {
            }
            mWeb.Dispose();
            site.Dispose();
            */
        }

//        public static void CreateTreeOrg(TermSet MSet,String mID)
//        {
//                int lcid = CultureInfo.CurrentCulture.LCID;
//                using (OleDbConnection mCo = new OleDbConnection(GetAppSetting(@"1CConnect")))
//                {
//                    mCo.Open();
//                    using (OleDbCommand cmd = new OleDbCommand())
//                    {
//                        cmd.CommandText = 
//@"SELECT sp._Description as Name,sp._Code as ID,sp1._Code as ParentID 
//FROM _Reference67 as sp 
//LEFT JOIN _Reference67 as sp1 ON sp1._IDRRef=sp._ParentIDRRef 
//WHERE sp._Code<>'09' AND sp1._Code =" + mID;
//                        cmd.CommandType = CommandType.Text;
//                        cmd.Connection = mCo;
//                        using (OleDbDataReader reader = cmd.ExecuteReader())
//                        {
//                            while (reader.Read())
//                            {
//                                Term mTerm = MSet.CreateTerm(reader["Name"].ToString(), lcid);
//                                mTerm.SetDescription(reader["ID"].ToString(), lcid);
//                                CreateTreeOrg1(mTerm, reader["ID"].ToString());
//                            }
//                            reader.Close();
//                        }
//                    }
//                    mCo.Close();
//                }
//        }

//        public static void CreateTreeOrg1(Term MSet, String mID)
//        {
//            int lcid = CultureInfo.CurrentCulture.LCID;
//            using (OleDbConnection mCo = new OleDbConnection(GetAppSetting(@"1CConnect")))
//            {
//                mCo.Open();
//                using (OleDbCommand cmd = new OleDbCommand())
//                {

//                    cmd.CommandText = 
//@"SELECT 
//sp._Description as Name,sp._Code as ID,sp1._Code as ParentID 
//FROM _Reference67 as sp 
//LEFT JOIN _Reference67 as sp1 ON sp1._IDRRef=sp._ParentIDRRef 
//WHERE sp._Code<>'09' AND sp1._Code =" + mID;

//                    cmd.CommandType = CommandType.Text;
//                    cmd.Connection = mCo;
//                    using (OleDbDataReader reader = cmd.ExecuteReader())
//                    {
//                        while (reader.Read())
//                        {
//                            Term mTerm = MSet.CreateTerm(reader["Name"].ToString(), lcid);
//                            mTerm.SetDescription(reader["ID"].ToString(), lcid);
//                            CreateTreeOrg1(mTerm, reader["ID"].ToString());
//                        }
//                        reader.Close();
//                    }
//                }
//                mCo.Close();
//            }
//        }


    } // Job . . .


}

